<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="commName">
        <el-input
          v-model="queryParams.commName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品描述" prop="commText">
        <el-input
          v-model="queryParams.commText"
          placeholder="请输入商品描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品标签" prop="commType">
        <el-select
          filterable
          v-model="queryParams.commType"
          placeholder="请选择商品标签"
          size="small"
          style="width: 240px"
        >
          <el-option-group
            v-for="group in statusOptions"
            :key="group.label"
            :label="group.label">
            <el-option
              v-for="dict in group.options"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
              :style="dict.cssClass"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="商品折扣" prop="commZhekou">
        <el-input
          v-model="queryParams.commZhekou"
          placeholder="请输入商品折扣"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <template slot="append">折</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fuw:comm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fuw:comm:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleDelete"
          v-hasPermi="['fuw:comm:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['fuw:comm:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="commId" width="180px"/>
      <el-table-column label="商品名称" align="center" prop="commName" :show-overflow-tooltip='true'/>
      <el-table-column label="商品描述" align="center" prop="commText" :show-overflow-tooltip='true'/>
      <el-table-column align="center" width="100" label="商品图片">
        <template scope="scope">
          <img :src="scope.row.commPicture" style="width:80px;height:80px;border:none;border-radius:3px;"
               onerror="this.src='http://localhost/dev-api/profile/upload/2021/12/16/2d1cde4d-3ba7-407f-82e1-0663e24318e4.jpg'"/>
        </template>
      </el-table-column>
      <el-table-column label="商品标签" align="center" prop="commType" :show-overflow-tooltip='true'/>
      <el-table-column label="商品单价" align="center" prop="commDanjia" width="80px"/>
      <el-table-column label="商品折扣" align="center" prop="commZhekou" width="80px"/>
      <el-table-column label="商品库存" align="center" prop="commKucun" width="80px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-goods"
            @click="handleAddCar(scope.row)"
            v-hasPermi="['fuw:car:addCar']"
          >购物车</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fuw:comm:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fuw:comm:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="commName">
          <el-input v-model="form.commName" placeholder="请输入商品名称" maxlength="30" show-word-limit/>
        </el-form-item>
        <el-form-item label="商品描述" prop="commText">
          <el-input v-model="form.commText" placeholder="请输入商品描述" type="textarea" maxlength="50" show-word-limit/>
        </el-form-item>

        <el-form-item label="图像预览" prop="commPicture">
          <el-upload :file-list="photoNow"
                     :limit="1"
                     :http-request="((val)=>{return myUpload(val)})"
                     :on-preview="handlePictureCardPreview"
                     :on-remove="((file,fileList)=>{return handleRemove(file,fileList)})"
                     :before-upload="handleBeforeUpload"
                     action=""
                     list-type="picture-card">
            <el-footer style="padding-right: 0px !important;padding-left: 0px !important;">请上传图片</el-footer>
            <!-- 点击进行图片放大预览  -->
            <i class="el-icon-plus" />
          </el-upload>
          <!-- 图片放大预览显示弹出框  -->
          <el-dialog :visible.sync="phone" :close-on-click-modal="false" :append-to-body="true">
            <img v-if="form.commPicture" :src="form.commPicture" width="100%" alt="">
          </el-dialog>

        </el-form-item>


        <el-form-item label="商品标签" prop="commType">
          <div class="sub-title">请选择分类标签及所属标签</div>
          <el-select
            v-model="selectValue"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择商品标签">
            <el-option-group
              v-for="group in statusOptions"
              :key="group.label"
              :label="group.label">
              <el-option
                v-for="dict in group.options"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
                :style="dict.cssClass"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="商品单价" prop="commDanjia">
          <el-input-number v-model="form.commDanjia" placeholder="请输入商品单价" :precision="3" :step="0.1" :min="0"/>
        </el-form-item>
        <el-form-item label="商品折扣" prop="commZhekou">
          <el-input v-model="form.commZhekou" placeholder="请输入商品折扣" style="width: 30%">
            <template slot="append">折</template>
          </el-input>
          <el-slider
            v-model="form.commZhekou"
            :max="9"
            show-stops
            style="width: 80%">
          </el-slider>
        </el-form-item>
        <el-form-item label="商品库存" prop="commKucun">
          <el-input-number v-model="form.commKucun" placeholder="请输入商品库存" :precision="0" :step="1" :min="0"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listComm, getComm, delComm, addComm, updateComm, exportComm } from "@/api/fuw/comm";
import { addCar } from "@/api/fuw/car";

export default {
  name: "Comm",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 图片上传
      formData: "",
      photoNow: [],
      phone: false,
      // 删除图片
      deletePhoto: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      commList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 商品标签数据字典
      statusOptions: [],
      // 新增/修改条目选择框
      selectValue: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        commName: null,
        commText: null,
        commPicture: null,
        commType: null,
        commDanjia: null,
        commZhekou: null,
        commKucun: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("fuw_comm_type").then(response => {
      let optionsList = this.getJsonCar(response.data, "listClass")
      //定义一个json对象
      let options = [
        {
          label: "诊断检测类",
          options: optionsList[0]
        },
        {
          label: "治疗器具类",
          options: optionsList[1]
        },
        {
          label: "保健康复类",
          options: optionsList[2]
        }
      ];
      this.statusOptions = options;
    });
    if(this.queryParams.commType != null){
      // 将字符串的选择框内容转换成字符串
      this.queryParams.commType = this.queryParams.commType.split(',');
    }
  },
  methods: {

    /**
     * 分割数组创建二维数组封装
     * @param Json 数组
     * @param key 需要分割的属性
     */
    getJsonCar(Json, key){
        //数据归类方法
        let kind = []; //存放属性标识
        let newArr = []; //返回的数据
        Json.map((item) => {
          // 判断key是否存在，不存在则添加
          if (!kind.includes(item[key])) {
            kind.push(item[key]); //kind添加新标识
            newArr.push([]); //添加数组
          }
          let index = kind.indexOf(item[key]); //返回带有标识在kind内的下标，判断加入哪个数组
          newArr[index].push(item); //将对象存入数组
        });
        return newArr;
    },
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listComm(this.queryParams).then(response => {
        this.commList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.deletePhoto = false;
      this.selectValue = [];
      // 清除图片
      this.photoNow = [];
      this.form = {
        commId: null,
        commName: null,
        commText: null,
        commPicture: null,
        commType: null,
        commDanjia: 0,
        commZhekou: 0,
        commKucun: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.queryParams.commType != null){
        // 将字符串的选择框内容转换成字符串
        this.queryParams.commType = this.queryParams.commType.toString();
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.commId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 添加购物车操作 */
    handleAddCar(row) {
      const commId = row.commId || this.ids
      //定义一个json对象
      let commCar = {
        id: null,
        personId: null,
        commId: commId
      };
      addCar(commCar).then(response => {
        this.msgSuccess("已添加购物车");
        this.open = false;
        this.getList();
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const commId = row.commId || this.ids
      getComm(commId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品信息";
        if(this.form.commPicture != null && this.form.commPicture != ''){
          this.photoNow = [{name: this.form.commPicture.split('/').pop(), url: this.form.commPicture}];
        }
        this.selectValue = this.form.commType.split(',');
      });
    },
    // 图片上传之前的判断
    handleBeforeUpload(file) {
      const isIMAGE = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt1M = file.size / 1024 / 500 < 1
      if (!isIMAGE) {
        this.$message.error('上传文件只能是jpg或png图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 500kb!')
      }
      return isIMAGE && isLt1M
    },
    // 删除上传的图片
    handleRemove(file, fileList) {
      this.form.commPicture = null
      this.deletePhoto = true
    },
    // 图片的放大预览
    handlePictureCardPreview(file) {
      this.phone = true
    },
    // 图片的上传调用方法
    myUpload(file) {
      this.deletePhoto = true;
      this.formData = file.file;
      this.form.commText = file.file.name.split('.')[0];
      this.form.commName = file.file.name.split('.')[0];
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        let formData = new FormData();
        console.log(this.deletePhoto);
        formData.append("fileNow", this.deletePhoto);
        formData.append("file", this.formData);
        formData.append("commId", this.form.commId)
        formData.append("commName", this.form.commName)
        formData.append("commText", this.form.commText)
        formData.append("commType", this.selectValue.toString())
        formData.append("commDanjia", this.form.commDanjia)
        formData.append("commZhekou", this.form.commZhekou)
        formData.append("commKucun", this.form.commKucun)

        if (valid) {
          if (this.form.commId != null) {
            updateComm(formData).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addComm(formData).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const commIds = row.commId || this.ids;
      this.$confirm('是否确认删除商品信息编号为"' + commIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delComm(commIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportComm(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>
/*去除upload组件过渡效果*/
.el-upload-list__item {
  transition: none !important;
}
</style>
